package com.leo.foodmaster.commons.config.security;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.json.JSONUtil;
import com.leo.foodmaster.commons.constants.HttpStatus;
import com.leo.foodmaster.commons.entity.Result;
import com.leo.foodmaster.commons.util.ServletUtils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;

/**
 * <p>
 * 自定义鉴权管理器
 * </p>
 *
 * @author ：Leo
 * @since ：2021-07-03 13:14
 */
@Component
@Slf4j
public class CustomAccessDecisionManager implements AccessDecisionManager {


    @SneakyThrows
    @Override
    public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> collection)
            throws AccessDeniedException, InsufficientAuthenticationException {
        // 3.用户所拥有的的权限集合
        Collection<? extends GrantedAuthority> userAuthorities = authentication.getAuthorities();
        List<String> collect = userAuthorities.stream().map(GrantedAuthority::getAuthority).collect(Collectors.toList());
        List<ConfigAttribute> list = SecurityConfig.createList(ArrayUtil.toArray(collect, String.class));

        // 4.检验用户是否有相应的权限
        AtomicBoolean hasAuthority = new AtomicBoolean(false);
        for (ConfigAttribute configAttribute : list) {
            // roleId是请求用户的角色(格式:ROLE_{roleId})，authorities是请求资源所需要角色的集合
            log.info("用户角色：{}", configAttribute);
            log.info("资源需要的角色：{}", collection);
            if (collection.contains(configAttribute)) {
                hasAuthority.set(true);
                break;
            }
        }

        if (!hasAuthority.get()) {
            throw new BadCredentialsException("用户没有访问该资源的权限!");
        }
    }

    @Override
    public boolean supports(ConfigAttribute configAttribute) {
        return true;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
